const validate = {
  isEmail(email) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  },

  isPhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },

  isPassword(password) {
    // 至少包含字母、数字和特殊字符中两种，长度6-20位
    const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/;
    return passwordRegex.test(password);
  },

  isIdCard(idCard) {
    const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return idCardRegex.test(idCard);
  },

  isUrl(url) {
    const urlRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    return urlRegex.test(url);
  },

  isNumber(value) {
    return !isNaN(parseFloat(value)) && isFinite(value);
  },

  isPositiveNumber(value) {
    return this.isNumber(value) && parseFloat(value) > 0;
  },

  isRequired(value) {
    return !!value;
  },

  validateForm(form) {
    const errors = {};

    // 遍历表单字段进行验证
    Object.keys(form).forEach((field) => {
      const value = form[field];
      const rules = form[field + 'Rules'];

      if (!rules) return;

      rules.forEach((rule) => {
        let isValid = true;
        let message = '';

        if (rule.required && !this.isRequired(value)) {
          isValid = false;
          message = `${rule.field} 是必填项`;
        } else if (rule.email && !this.isEmail(value)) {
          isValid = false;
          message = `${rule.field} 格式不正确`;
        } else if (rule.phone && !this.isPhone(value)) {
          isValid = false;
          message = `${rule.field} 格式不正确`;
        } else if (rule.password && !this.isPassword(value)) {
          isValid = false;
          message = `${rule.field} 格式不正确`;
        } else if (rule.idCard && !this.isIdCard(value)) {
          isValid = false;
          message = `${rule.field} 格式不正确`;
        } else if (rule.url && !this.isUrl(value)) {
          isValid = false;
          message = `${rule.field} 格式不正确`;
        } else if (rule.number && !this.isNumber(value)) {
          isValid = false;
          message = `${rule.field} 必须是数字`;
        } else if (rule.positiveNumber && !this.isPositiveNumber(value)) {
          isValid = false;
          message = `${rule.field} 必须是正数`;
        }

        if (!isValid) {
          errors[field] = message;
        }
      });
    });

    return errors;
  }
};

export default validate;